﻿using Models;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using yymbBLL;

namespace WebApp_WB.Controllers
{
    [ValidateInput(false)]
    public class HomeController : Controller
    {
        private IndexManger db = new IndexManger();
        private yymbDBEntities _efdb = new yymbDBEntities();
        //首页
        public ActionResult Index()
        {
            ViewData["TOP"] = db.GetTopFollow();
            ViewData["News"] = db.GetNewUser();
            ViewData["MBlog"] = db.GetNewMBlogs();
            ViewBag.SumWB = db.SumWB();
            ViewBag.FwMic = _efdb.Microblog.Include("Information").ToList();
            return View();
        }
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            return View();
        }       
        //登录页
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(FormCollection form)//提交登录
        {
            string name = form["name"];
            string pwd = form["pwd"];
            User user = db.Login(name, pwd);
            if (user!=null)
            {
                FormsAuthentication.SetAuthCookie(name, false);
                Session["name"] = name;
                Session["UserID"] = user.UserID;
                return RedirectToAction("Index");

            }
            return View();
        }
        //注册页
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public string Register(string email, string phone, string pwd)//提交注册
        {
            if (email == "" || phone == "" || pwd == "")
            {

                return "注册失败，信息均不可为空!";
            }
            else
            {
                if (phone.Length != 11)
                {

                    return "手机号格式不正确!";
                }
                else
                {
                    if (pwd.Length < 6 || pwd.Length > 20)
                    {

                        return "密码必须在6至20位!";
                    }
                    else
                    {
                        User user = new User
                        {
                            E_mail = email,
                            Mobile = phone,
                            Password = pwd,
                            Creation = DateTime.Now
                        };
                        if (db.Register(user))
                        {
                            int id = db.GetOneUser(user.E_mail, user.Password);
                            Information info = new Information
                            {
                                UserID = id,
                                Nickname = email,
                            };
                            db.AddInfo(info);
                            return "";
                        }

                        return "注册失败！";
                    }
                }
            }
        }
        public ActionResult Layout()//销毁Session
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            Session.Abandon();
            return RedirectToAction("Index");
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="size"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public JsonResult Getmblog(int size,int index)
        {
            _efdb.Configuration.ProxyCreationEnabled = false;
            var data = _efdb.Microblog.Include("Information").Include("WB_pic").Include("Comment").OrderByDescending(n => n.Release_time).
                    Select(n => new {
                        MbID = n.MbID,
                        Type = n.Type,
                        Content = n.Content,
                        Url = n.Url,
                        Release_time = n.Release_time.ToString(),
                        Forward = _efdb.Microblog.Where(m => m.FwID == n.MbID).ToList().Count(),
                        Likes = n.Likes.Count(),
                        UserID = n.UserID,
                        Photo = n.Information.Photo,
                        Nickname = n.Information.Nickname,
                        WB_pic = n.WB_pic,
                        Comment = n.Comment.ToList(),
                        Fw = _efdb.Microblog.Where(m=>m.MbID==n.FwID).Select(m=>new {
                            MbID = m.MbID,
                            Type = m.Type,
                            Content = m.Content,
                            Url = m.Url,
                            Release_time = m.Release_time.ToString(),                        
                            UserID = m.UserID,
                            Photo = m.Information.Photo,
                            Nickname = m.Information.Nickname,
                            WB_pic = m.WB_pic,
                        }).ToList()
                    }).
                    Skip(size * (index - 1)).Take(size).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="Mbid"></param>
        /// <returns></returns>
        public int Fabulous(int Mbid)
        {
            LikeManger db = new LikeManger();
            int Userid =Convert.ToInt32(Session["UserID"].ToString());
            return db.Fabulous(Mbid, Userid);
        }
        /// <summary>
        /// 调用布局页显示评论
        /// </summary>
        /// <param name="MbID"></param>
        /// <returns></returns>
        public ActionResult ShowComm(int MbID)
        {
            ViewBag.Comm = db.GetComm(MbID);
            return PartialView("_CommPage",MbID);
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="mbid"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public string AddComm(int mbid,string result,int? rid)
        {
            string text = result.IndexOf(":")>0?result.Substring(result.IndexOf(":")):result;
            int Userid = Convert.ToInt32(Session["UserID"].ToString());
            Comment comment = new Comment
            {
                Comments = text,
                Comment_time = DateTime.Now,
                UserID = Userid,
                MbID = mbid,
                ReplyID = rid
            };
            if (db.AddComment(comment))
            {
                return "评论成功";
            }
            return "评论失败,原因未知";
        }
        /// <summary>
        /// 回复了谁的评论
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [Authorize]
        public string HuiComm(int rid,int uid)
        {
            int Userid = Convert.ToInt32(Session["UserID"].ToString());
            string name = Session["name"].ToString();
            string rname = _efdb.Information.Where(n => n.UserID == uid).Select(n => n.Nickname).FirstOrDefault();
            return name + "@" + rname+":";
        }
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="commid"></param>
        /// <returns></returns>
        [Authorize]
        public string DelComm(int commid)
        {
            if (db.DelComment(commid))
            {
                return "删除成功";
            }
            return "删除失败,原因未知";
        }
        /// <summary>
        /// 转发微博
        /// </summary>
        /// <param name="mbid"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        [Authorize]
        public JsonResult AddFwmb(int mbid,string result)
        {
            int Userid = Convert.ToInt32(Session["UserID"].ToString());
            Microblog micr = new Microblog
            {
                Type = "转发",
                Content = result,
                Url = null,
                Release_time = DateTime.Now,
                UserID = Userid,
                FwID = mbid
            };
            return Json(new { bl=db.AddFwmb(micr)},JsonRequestBehavior.AllowGet);
        }
        public string ZMric(int rid)
        {
            string rname = _efdb.Information.Where(n => n.UserID == rid).Select(n => n.Nickname).FirstOrDefault();
            return rname;
        }
    }
}